[進階 js 01] 變數的資料型態


Posted by tzutzu858 on 2021-03-15

七種資料型態
primitive type 原始型態

  1. null
  2. undefined
  3. string
  4. number
  5. boolean
  6. symbol(ES6)

其他都是 object 物件

  1. object(array, function ,date)

primitive type 和 object 最大差別,primitive type 是 Immutable 不能改變
這時候可能會覺得奇怪不是可以改變嗎?

var a = 10
a = 20

這樣 a 不就改變了嗎?
這邊的改變不是這個意思,上述是重新賦值
改變的例子如下 :

var str = 'hello'
str.toUpperCase()
console.log(str)

// log 出來的 str 的值還是 hello,並沒有改變

str.toUpperCase() 這行的意思並不是改變他原本的值,而是回傳一個新的值
所以是可以接收一個新的值

var str = 'hello'
var newStr = str.toUpperCase()
console.log(newStr)

// log 出來就是新的值 HELLO

這點就跟 array 很不一樣

var arr = [1]
arr.push(2)
console.log(arr)

// 出來結果是真的去改變 arr ,變成 [1, 2]


怎麼知道變數的型態是什麼?用 typeof

console.log(typeof 10)  //出來是 number
console.log(typeof 'hello')  //出來是 string
console.log(typeof undefined)  //出來是 undefined
console.log(typeof true)  //出來是 boolean

但有一個最讓人混淆的是

console.log(null) //出來是 object

這個是 javascript 最廣為人知的一個 bug ,但也沒人敢修他,因為修了可能很多東西會壞掉
在 mozilla 的文章有提到成因

In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value. The type tag for objects was 0. null was represented as the NULL pointer (0x00 in most platforms). Consequently, null had 0 as type tag, hence the typeof return value "object".

文章最上面還有做一個表格


但沒辦法用 typeof 知道一個變數是不是 Array
可以用

console.log(Array.isArray([]))

typeof 有時也會去檢查一個變數有沒有用
如果直接用 console.log(a) 程式會出錯,寫 a is not undefined
所以有些判斷會這樣檢查

if (typeof a !== 'undefined' ) {
    console.log(a)
}

//'undefined' 是一個字串

結果:
沒有 a ,就不會 log 出任何東西,而程式也不會報錯
有 a ,就印出 a 的值


除了用 typeof 來檢測型態還有其他方法,相對來說會更準確一點

console.log(Object.prototype.toString.call(1))

// 第一個就傳要檢查的東西,比如說 1
// 便會回傳 [object Number]

console.log(Object.prototype.toString.call('1'))
// 回傳 [object String]

console.log(Object.prototype.toString.call(null))
// 回傳 [object Null]

在一些比較舊的瀏覽器,並沒有 Array.isArray([]) 這個方法可以用,那就用 Object.prototype.toString.call() 比較方便










Related Posts

部署 (1) —— 建立 AWS EC2 主機及 SSH 連線

部署 (1) —— 建立 AWS EC2 主機及 SSH 連線

Express Web App 靜態、動態路由

Express Web App 靜態、動態路由

MTR04_0625

MTR04_0625


Comments